<?php
/**
 * Created by PhpStorm.
 * User: 丶晓
 * Date: 2017/9/20
 * Time: 9:37
 */

namespace app\api\controller;


use app\api\common\Tools;
use app\common\Base;
use app\api\model\DataModel;
use think\Config;
use think\Controller;
use think\Log;
use think\Request;

class Open extends Controller
{

    private $appid;
    private $appsecret;

    // +++++++++++++++++++++++++++++++++++++++++++++++++
    // | 第三方平台 API 接口
    // +++++++++++++++++++++++++++++++++++++++++++++++++
    public function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub
        $this->appid = Config::get('wxopen.appid');
        $this->appsecret = Config::get('wxopen.appsecret');
    }

    // +++++++++++++++++++++++++++++++++++++++++++++++++
    // |  获取（刷新）授权公众号或小程序的接口调用凭据（令牌）
    // +++++++++++++++++++++++++++++++++++++++++++++++++

    public function get_access_token($id)
    {
        $miniModel = new DataModel();
        //刷新小程序access_token
        $this->refresh_access_token($id);
        return $miniModel->selectInfo('authorizer_access_token', ['id' => $id]);
    }

    // +++++++++++++++++++++++++++++++++++++++++++++++++
    // |    获取第三方平台component_access_token
    // +++++++++++++++++++++++++++++++++++++++++++++++++

    public function refresh_access_token($id)
    {
        $miniModel = new DataModel();
        $res = [
            'component_appid' => $this->appid,
            'authorizer_appid' => $miniModel->selectInfo('authorizer_appid', ['id' => $id]),
            'authorizer_refresh_token' => $miniModel->selectInfo('authorizer_refresh_token', ['id' => $id])
        ];
        //重新刷新access_token并更新数据库
        $component_access_token = json_decode($this->get_component_access_token(), true)['data']['component_access_token'];
        $jsonstr = json_encode($res, JSON_UNESCAPED_UNICODE);
        $url = 'https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token=' . $component_access_token;
        $result = Base::_requestPost($url, $jsonstr);
        $data = json_decode($result, true);
        $data['id'] = $id;
        $data['add_time'] = date('y-m-d H:i:s', time());
        return $miniModel->changeInfo('all_authorizer', $data);
    }

    // +++++++++++++++++++++++++++++++++++++++++++++++++
    // |  查询ticket
    // +++++++++++++++++++++++++++++++++++++++++++++++++

    public function get_component_access_token()
    {
        $ticket = $this->get_ticket();
        $data = [
            'component_appid' => $this->appid,
            'component_appsecret' => $this->appsecret,
            'component_verify_ticket' => $ticket
        ];
        $jsonstr = json_encode($data);
        $url = 'https://api.weixin.qq.com/cgi-bin/component/api_component_token';
        $result = Base::_requestPost($url, $jsonstr);
        $res = json_decode($result, true);
        return $res ? Tools::success('request success!', $res) : Tools::error('request error!');
    }

    // +++++++++++++++++++++++++++++++++++++++++++++++++
    // |   获取授权小程序的access_token
    // +++++++++++++++++++++++++++++++++++++++++++++++++

    public function get_ticket()
    {
        $DataModel = new DataModel();
        return $DataModel->selectInfo('get_ticket');
    }

    // ++++++++++++++++++++++++++++++++++++++++++++
    // |  获取预授权码pre_auth_code
    // ++++++++++++++++++++++++++++++++++++++++++++
    public function get_pre_auth_code()
    {
        $component_access_token = json_decode($this->get_component_access_token(), JSON_UNESCAPED_UNICODE)['data']['component_access_token'];
        $url = 'https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token=' . $component_access_token;
        $data['component_appid'] = $this->appid;
        $jsonstr = json_encode($data);
        $Base = new Base();
        $result = $Base->_requestPost($url, $jsonstr);
        $res = json_decode($result, true);
        $Tools = new Tools();
        return $Tools->success('request success!', $res);
    }

    // +++++++++++++++++++++++++++++++++++++++++++++++++
    // |   查询最新一次提交的审核状态
    // +++++++++++++++++++++++++++++++++++++++++++++++++
    public function get_last_statu($access_token = null)
    {
        $Tools = new Tools();
        if (!isset($_GET['access_token']) and empty($access_token) and empty($_GET['access_token'])) {
            return $Tools->error('request lost access_token');
        }
        $access_token = empty($access_token) ? $_GET['access_token'] : $access_token;
        $url = 'https://api.weixin.qq.com/wxa/get_latest_auditstatus?access_token=' . $access_token;
        $Base = new Base();
        $RES = $Base->_requestGet($url);
        return $Tools->success('request success', $RES);
    }

    // +++++++++++++++++++++++++++++++++++++++++++++++++
    // |   修改小程序线上代码的可见状态 @Xiao
    // +++++++++++++++++++++++++++++++++++++++++++++++++
    public function change_visitstatus($access_token = null, $action = 'close')
    {
        $Tools = new Tools();
        if (!Request::instance()->isPost()) {
            return $Tools->error('must be Post data!');
        }
        $access_token = isset($_POST['accesstoken']) ? $_POST['accesstoken'] : $access_token; // 小程序授权的authorizer_access_token
        $action = isset($_POST['action']) ? $_POST['action'] : $action; // close为不可见，open为可见
        $action = ($action and $action != 'close') ? 'open' : 'close';

        if (empty($access_token) or empty($action)) {
            return $Tools->error('request fail');
        }

        $url = 'https://api.weixin.qq.com/wxa/change_visitstatus?access_token=' . $access_token; // 请求地址
        $Base = new Base();
        $RES = $Base->_requestPost($url, json_encode(['action' => $action]), JSON_UNESCAPED_UNICODE);
        return $Tools->success('request success', $RES);
    }

    // +++++++++++++++++++++++++++++++++++++++++++++++++
    // |   修改服务器地址 @Xiao
    // +++++++++++++++++++++++++++++++++++++++++++++++++
    public function modify_domain($access_token = null, $action = null, $requestdomain = null, $wsrequestdomain = null, $uploaddomain = null, $downloaddomain = null)
    {
        $Tools = new Tools();
        $access_token = isset($_POST['accesstoken']) ? $_POST['accesstoken'] : $access_token; // 小程序授权的authorizer_access_token
        $action = isset($_POST['action']) ? $_POST['action'] : $action; // add添加, delete删除, set覆盖, get获取。当参数是get时不需要填四个域名字段。
        $requestdomain = json_decode(isset($_POST['requestdomain']) ? $_POST['requestdomain'] : $requestdomain); // request合法域名
        $wsrequestdomain = json_decode(isset($_POST['wsrequestdomain']) ? $_POST['wsrequestdomain'] : $wsrequestdomain); // socket合法域名
        $uploaddomain = json_decode(isset($_POST['uploaddomain']) ? $_POST['uploaddomain'] : $uploaddomain);  // uploadFile合法域名
        $downloaddomain = json_decode(isset($_POST['downloaddomain']) ? $_POST['downloaddomain'] : $downloaddomain);  // downloadFile合法域名

        $url = 'https://api.weixin.qq.com/wxa/modify_domain?access_token=' . $access_token; // 请求地址
        $Base = new Base();
        $data = $action == 'get' ? [
            'action' => $action
        ] : [
            'action' => $action,
            'requestdomain' => $requestdomain,
            'wsrequestdomain' => $wsrequestdomain,
            'uploaddomain' => $uploaddomain,
            'downloaddomain' => $downloaddomain
        ];
        $RES = $Base->_requestPost($url, json_encode($data), JSON_UNESCAPED_UNICODE);
        return $Tools->success('request success', $RES);
    }

    // +++++++++++++++++++++++++++++++++++++++++++++++++
    // |   发送客服消息
    // +++++++++++++++++++++++++++++++++++++++++++++++++
    public function sendMessagesToUser($access_token = null, $message = null, $touser = null, $msgtype = null)
    {
        $access_token = isset($_POST['access_token']) ? $_POST['access_token'] : $access_token;
        $message = isset($_POST['message']) ? $_POST['message'] : $message;
        $touser = isset($_POST['touser']) ? $_POST['touser'] : $touser;
        $msgtype = isset($_POST['msgtype']) ? $_POST['msgtype'] : $msgtype;

        $Tools = new Tools();
        if (empty($access_token) or empty($touser) or empty($msgtype) or empty($message)) {
            $Tools->error('request fail!');  // 请求失败
        }

        $api_url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=' . $access_token;

        $POST = [  // 预拼装发送消息内容，请注意回复的消息类型
            'touser' => $touser,
            'msgtype' => $msgtype
        ];
        switch ($msgtype) {
            case 'text': // 发送文本消息
                $POST['text']['content'] = $message;
                break;
            case 'image': // 发送图片消息
                $POST['image']['media_id'] = $message;
                break;
            case 'link': // 发送图文链接 每次可以发送一个图文链接
                $data = json_decode($message);
                $POST['link']['title'] = $data->title;
                $POST['link']['description'] = $data->description;
                $POST['link']['url'] = $data->url;
                $POST['link']['thumb_url'] = $data->thumb_url;
                break;
            case 'miniprogrampage': // 发送小程序卡片
                $data = json_decode($message);
                $POST['miniprogrampage']['title'] = $data->title;
                $POST['miniprogrampage']['pagepath'] = $data->pagepath;
                $POST['miniprogrampage']['thumb_media_id'] = $data->thumb_media_id;
                break;
            default:
                $Tools->error('Type miss!');
                break;
        }
        $SEND = json_encode($POST, JSON_UNESCAPED_UNICODE);
        $RES = $Tools->_requestPost($api_url, $SEND);
        if (!isset($RES['errcode']) or $RES['errcode'] != 0) {
            Log::error('+++++++++++++++++++  客服消息回调接口  +++++++++++++++++++++');
            Log::error('失败信息：' . $RES);
            return $Tools->error('send fail!');
        }
        return $Tools->success('send success!');
    }


}
